<template>
  <div class="searchbox">
    <header class="header">
      <van-nav-bar left-arrow
        @click-right="goSearch"
        @click-left="$router.back()"
      >
        <template #right>
          搜索
        </template>
        <template #title>
          <van-search v-model="value" shape="round" placeholder="请输入搜索关键词" />
        </template>
      </van-nav-bar>
    </header>
    <div class="content">
      <div class="hot-search s-box">
        <h4>热门搜索：</h4>
        <div class="list">
          <van-tag v-for="item in hot" :key="item" plain type="primary" size="large" @click="goSearch(item)">{{item}}</van-tag>
        </div>
      </div>
      <div class="history-search s-box">
        <h4>搜索历史：</h4>
        <div class="list">
          <van-tag v-for="(item,idx) in history" :key="item.searchId" plain type="primary" closeable @close="close(item.searchId, idx)" size="large" @click="goSearch(item.searchText)">{{item.searchText}}</van-tag>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Vue from 'vue'
import { NavBar, Search, Tag, Toast } from 'vant'

import { getSearch, addSearch, delSearch } from '../../api/index.js'

Vue.use(NavBar)
Vue.use(Search)
Vue.use(Tag)
Vue.use(Toast)

export default {
  data () {
    return {
      value: '',
      hot: ['手机', '电脑', '美妆个护', '女装', '男装', '笔记本'],
      history: []
    }
  },
  methods: {
    close (id, i) {
      delSearch({
        userId: localStorage.getItem('userId'),
        searchId: id
      }).then(res => {
        console.log('删除搜索历史关键字成功')
        this.history.splice(i, 1)
      })
    },
    goSearch (val) {
      let st = ''
      if (typeof val !== 'object') {
        st = val
      } else {
        st = this.value
      }
      if (st === '') {
        Toast('请输入搜索关键字')
        return null
      }
      addSearch({
        userId: localStorage.getItem('userId'),
        searchText: st
      }).then(res => {
        // console.log('添加成功，可以跳转到搜索页面了')
        getSearch({
          userId: localStorage.getItem('userId')
        }).then(res => {
          this.history = res.data.data
          console.log(this.history)
        })
      })
      this.$router.push('/searchres/' + st)
    }
  },
  mounted () {
    getSearch({
      userId: localStorage.getItem('userId')
    }).then(res => {
      this.history = res.data.data
      console.log(this.history)
    })
  }
}
</script>

<style lang="scss" scoped>

.searchbox{
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
  .content{
    flex: 1;
    overflow: auto;
  }
    .hot-search{
    margin: 0.12rem;
    .van-tag{
      margin: 0.03rem;
    }
  }
  .history-search{
    margin: 0.1rem;
    .van-tag{
      margin: 0.02rem;
    }
  }
}
</style>
